package utils;
import com.aton.db.Config;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import services.SystemParamService;

public class RedisUtil {
	private static int PORT=Integer.parseInt(SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("JEDIS_PORT")));
	private static String URL=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("JEDIS_URL"));
	private static String PASSWORD=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("JEDIS_PASSWORD"));
	private static int MAX_ACTIVE = Integer.parseInt(SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("JEDIS_MAX_ACTIVE")));;
	private static int MAX_IDLE = Integer.parseInt(SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("JEDIS_MAX_IDE")));;
	private static int MAX_WAIT = Integer.parseInt(SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("JEDIS_MAX_WAIT")));;
	private static int TIMEOUT = Integer.parseInt(SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("JEDIS_TIMEOUT")));;
	private static boolean TEST_ON_BORROW = Boolean.parseBoolean(SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("JEDIS_TEST_ON_BORROW")));
	private static JedisPool jedisPool = null;
	static {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxActive(MAX_ACTIVE);
			config.setMaxIdle(MAX_IDLE);
			config.setMaxWait(MAX_WAIT);
			config.setTestOnBorrow(TEST_ON_BORROW);
			if(PASSWORD==null||"".equals(PASSWORD))
			jedisPool = new JedisPool(config, URL, PORT, TIMEOUT);
			else
				jedisPool=new JedisPool(config, URL, PORT, TIMEOUT, PASSWORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized static Jedis getJedis() {
		try {
			if (jedisPool != null) {
				Jedis resource = jedisPool.getResource();
				return resource;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 释放jedis资源
	 * 
	 * @param jedis
	 */
	public static void returnResource(final Jedis jedis) {
		if (jedis != null) {
			jedisPool.returnResource(jedis);
		}
	}
}
